package com.ruicar.afs.cloud.basic.cms.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.basic.common.condition.PrepaymentRecordQueryCondition;
import com.ruicar.afs.cloud.basic.common.entity.*;
import com.ruicar.afs.cloud.basic.common.service.*;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.LoanInfoVo;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.AssetTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ContractStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.PersonRoleTypeEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description: 多品合同对接聚合层 贷款信息查询
 */
@Slf4j
@RestController
@RequestMapping("/icosLoanInfo")
@AllArgsConstructor
public class IcosLoanInfoController {

    private final BasicMainInfoService basicMainInfoService;
    private final BasicCustBaseInfoService basicCustBaseInfoService;
    private final BasicRepaymentPlanService basicRepaymentPlanService;
    private final BasicContractCustRelationService basicContractCustRelationService;
    private final BasicBankCardService basicBankCardService;
    private final BasicFinancialAgreementService basicFinancialAgreementService;

    @ApiOperation(value = "贷款信息查询")
    @PostMapping("/getLoanInfo")
    public IResponse<List<LoanInfoVo>> getLoanInfo(@RequestBody PrepaymentRecordQueryCondition condition){
        if (EmptyUtils.isEmpty(condition.getContractNo()) && EmptyUtils.isEmpty(condition.getCertNo())){
            return IResponse.fail("证件号或合同号，必须要传值其中的一项");
        }
        List<String> contractNoList = new ArrayList<>();
        if (EmptyUtils.isNotEmpty(condition.getCertNo())){
            List<BasicCustBaseInfo> custPersonalDetails = basicCustBaseInfoService.list(Wrappers.<BasicCustBaseInfo>query().lambda()
                    .eq(BasicCustBaseInfo::getCertNo,condition.getCertNo())
            );
            if (EmptyUtils.isNotEmpty(custPersonalDetails)){
                List<String> custNos = custPersonalDetails.stream().map(BasicCustBaseInfo::getCustNo).collect(Collectors.toList());
                List<BasicContractCustRelation> relationList = basicContractCustRelationService.list(Wrappers.<BasicContractCustRelation>query().lambda()
                        .in(BasicContractCustRelation::getCustNo,custNos)
                        .eq(BasicContractCustRelation::getCustRole, PersonRoleTypeEnum.MAIN_PERSON)
                );
                if (EmptyUtils.isNotEmpty(relationList)){
                    relationList.forEach(relation -> {
                        contractNoList.add(relation.getContractNo());
                    });
                }
            }
        }
        if (EmptyUtils.isEmpty(condition.getCertNo())&&EmptyUtils.isNotEmpty(condition.getContractNo())){
            contractNoList.add(condition.getContractNo());
        }

        List<LoanInfoVo> loanInfoVoList = new ArrayList<>();
        /**  合同基本信息 by ZC.GUO  **/
        List<BasicMainInfo> mainInfoList = basicMainInfoService.list(Wrappers.<BasicMainInfo>query().lambda()
                .in(BasicMainInfo::getContractNo,contractNoList)
        );
        if (EmptyUtils.isNotEmpty(mainInfoList)){
            mainInfoList.forEach(mainInfo ->{
                LoanInfoVo loanInfoVo = new LoanInfoVo();
                loanInfoVo.setApplyNo(mainInfo.getApplyNo());
                loanInfoVo.setSettleDate(mainInfo.getSettleDate());
                /**  逾期合同 by ZC.GUO  **/
                if (ContractStatusEnum.overdue.equals(mainInfo.getContractStatus())){
                    loanInfoVo.setContractStatus("1");
                }
                /**  结清合同 by ZC.GUO  **/
                else if (ContractStatusEnum.advanceSettle.equals(mainInfo.getContractStatus())
                        ||ContractStatusEnum.normalSettle.equals(mainInfo.getContractStatus())
                        ||ContractStatusEnum.writeOff.equals(mainInfo.getContractStatus())){
                    loanInfoVo.setContractStatus("2");
                }
                /**  正常合同 by ZC.GUO  **/
                else {
                    loanInfoVo.setContractStatus("3");
                }
                /**  是否激活  已激活=1 未激活=0 by ZC.GUO  **/
                loanInfoVo.setCaseStatus("1");
                /**  客户信息 by ZC.GUO  **/
                BasicContractCustRelation relation = basicContractCustRelationService.getOne(Wrappers.<BasicContractCustRelation>query().lambda()
                        .eq(BasicContractCustRelation::getContractNo,mainInfo.getContractNo())
                        .eq(BasicContractCustRelation::getCustRole, PersonRoleTypeEnum.MAIN_PERSON)
                );
                if (EmptyUtils.isNotEmpty(relation)){
                    BasicCustBaseInfo custBaseInfo = basicCustBaseInfoService.getOne(Wrappers.<BasicCustBaseInfo>query().lambda()
                            .eq(BasicCustBaseInfo::getCustNo,relation.getCustNo())
                    );
                    if (EmptyUtils.isNotEmpty(custBaseInfo)){
                        loanInfoVo.setCertNo(custBaseInfo.getCertNo());
                    }
                }
                /**  银行卡信息 by ZC.GUO  **/
                BasicBankCard bankCard = basicBankCardService.getOne(Wrappers.<BasicBankCard>query().lambda()
                        .eq(BasicBankCard::getContractNo,mainInfo.getContractNo())
                );
                if (EmptyUtils.isNotEmpty(bankCard)){
                    loanInfoVo.setAccountNo(bankCard.getAccountNo());
                }
                /**  金融协议信息 by ZC.GUO  **/
                BasicFinancialAgreement financialAgreement = basicFinancialAgreementService.getOne(Wrappers.<BasicFinancialAgreement>query().lambda()
                        .eq(BasicFinancialAgreement::getContractNo,mainInfo.getContractNo())
                        .eq(BasicFinancialAgreement::getCostType, AssetTypeEnum.CAR_AMT)
                );
                if (EmptyUtils.isNotEmpty(financialAgreement)){
                    loanInfoVo.setCustRate(financialAgreement.getCustRate());
                    loanInfoVo.setLoanTrem(financialAgreement.getLoanTerm());
                    loanInfoVo.setDownPayAmt(financialAgreement.getDownPayAmt());
                }
                /**  还款计划相关信息 by ZC.GUO  **/
                List<BasicRepaymentPlan> repaymentPlanList = basicRepaymentPlanService.list(Wrappers.<BasicRepaymentPlan>query().lambda()
                        .eq(BasicRepaymentPlan::getContractNo,mainInfo.getContractNo())
                        .ne(BasicRepaymentPlan::getTermNo, BigDecimal.ZERO.intValue())
                        .orderByAsc(BasicRepaymentPlan::getTermNo)
                );
                BasicRepaymentPlan repaymentPlan = basicRepaymentPlanService.calculateRepaymentInfo(repaymentPlanList);
                loanInfoVo.setTotalPrinciple(repaymentPlan.getTotalPrinciple());
                loanInfoVo.setTotalInterest(repaymentPlan.getTotalInterest());
                loanInfoVo.setTotalRent(repaymentPlan.getTotalRent());
                loanInfoVo.setPaidTerms(repaymentPlan.getPaidTerms());
                loanInfoVo.setLastPayDate(repaymentPlan.getLastPayDate());
                loanInfoVo.setFirstPayDate(repaymentPlan.getFirstPayDate());
                loanInfoVo.setUnpaidRent(repaymentPlan.getUnpaidRent());
                loanInfoVo.setPrePayDate(repaymentPlan.getPrePayDate());
                loanInfoVo.setDueDate(repaymentPlan.getDueDate());
                if (EmptyUtils.isNotEmpty(repaymentPlan.getReceivableRent())){
                    if (EmptyUtils.isEmpty(repaymentPlan.getActualRent())){
                        repaymentPlan.setActualRent(BigDecimal.ZERO);
                    }
                    loanInfoVo.setRemainAmt(repaymentPlan.getReceivableRent().subtract(repaymentPlan.getActualRent()));
                }
                loanInfoVoList.add(loanInfoVo);
            });
        }
        return IResponse.success(loanInfoVoList);
    }

}
